<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更新用户信息</span>
    </div>
    <el-form ref="userinfo" label-width="80px" :model="userinfo" :rules="rules">
      <el-form-item label="登录账号" prop="username">
        <el-input v-model="userinfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userinfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userinfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updataUser">确认修改</el-button>
        <el-button @click="resetForm('userinfo')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updataUserAPI } from '@/api/user'
export default {
  name: 'UserInfo',
  data() {
    return {
      // userinfo: {
      //   username: this.$store.state.user.user.username,
      //   nickname: this.$store.state.user.user.nickname,
      //   email: this.$store.state.user.user.email
      // }

      userinfo: { ...this.$store.state.user.user },

      rules: {
        nickname: [
          { required: true, message: '昵称必填', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱必填', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    resetForm(formName) {
      this.userinfo = { ...this.$store.state.user.user }
      this.$refs[formName].resetFields()
    },
    updataUser() {
      this.$refs.userinfo.validate(async valid => {
        if (!valid) return
        const { data: res } = await updataUserAPI(this.userinfo)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$store.dispatch('user/getUser')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-card {
  font-size: 13px;
}
.el-form {
  width: 500px;
}
</style>
